﻿using Admin.Repository.Menus;
using Admin.Repository.RoleMenus;
using Admin.Repository.Roles;
using Admin.RoleMenus;
using Admin.Roles;
using Admin.Service.RoleMenus.DTO;
using BLL.UserInfos.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin.Service.RoleMenus
{
    public class RoleMenuService : IRoleMenuService
    {
        private readonly IRoleMenuRepository roleMenuRepository;
        private readonly IMenuRepository menu;
        private readonly IRoleRepository role;

        public RoleMenuService(IRoleMenuRepository roleMenuRepository,IMenuRepository menu,IRoleRepository role)
        {
            this.roleMenuRepository = roleMenuRepository;
            this.menu = menu;
            this.role = role;
        }

        /// <summary>
        /// 修改分配权限
        /// </summary>
        /// <returns></returns>
        public int AddRoleMenu(AddRoleMenuDto dto)
        {
            //删除
            roleMenuRepository.Delete(x => x.RoleId == dto.RoleId);

            foreach (var item in dto.MenuId)
            {
                roleMenuRepository.Update(new RoleMenu
                {
                    MenuId = item,
                    RoleId = dto.RoleId,
                });
            }

            return 1;
        }

        /// <summary>
        /// 反填权限
        /// </summary>
        /// <returns></returns>
        public RestDto<RoleMenuDto> FillRoleMenu(int id)
        {
            try
            {
                var data = role.QueryId(id);

                return new RestDto<RoleMenuDto>
                {
                    Code = 200,
                    Data = new RoleMenuDto
                    {
                        RoleId = id,
                        MenuId = roleMenuRepository.QueryList(x => x.RoleId == id).Select(x => x.MenuId).ToArray()
                    }
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
